package com.ruoyi.web.controller.tool;


import com.kt.mes.domain.*;
import com.kt.mes.opc.OpcClientUtil;
import com.kt.mes.service.*;
import com.kt.mes.util.OpcUtil;
import com.kt.mes.util.WebSocketServer;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

@Api("外部调用接口")
@RestController
@RequestMapping("/ai")
public class ApiController extends BaseController {

    @Autowired
    private IOrderProductService orderProductService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IMaterialService materialService;

    @Autowired
    private IWorkPlanItemService workPlanItemService;

    @Autowired
    private IProductStoreListService productStoreListService;

    @Autowired
    private IProlSiteService prolSiteService;

    @Autowired
    private IStorageInRecordService storageInRecordService;

    //创建订单
    @ApiOperation("创建订单")
    @PostMapping("/addOrder")
    public AjaxResult addOrder(String color, int quantity) {
        System.out.println("AI 调用订单");
        System.out.println("color=" + color);
        System.out.println("qty=" + quantity);


        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setProQty(quantity);
        orderProduct.setCreateBy("APP");

        if (color.equals("yellow")) {
            orderProduct.setPpId("521");
        }
        if (color.equals("blue")) {
            orderProduct.setPpId("522");
        }


        orderProductService.insertOrderProduct(orderProduct);

        try {
            WebSocketServer.sendInfo("refresh", "order_page");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    //查询所有订单
    @ApiOperation("查询所有订单")
    @GetMapping("/getOrderList")
    public AjaxResult getOrderList(OrderProduct orderProduct) {


        List<OrderProduct> list = orderProductService.selectOrderProductList(orderProduct);

        return AjaxResult.success(list);

    }

    @ApiOperation("查询单个订单")
    @GetMapping("/findOrderById/{oId}")
    public AjaxResult findOrderById(@PathVariable("oId") String oId) {
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOpId(oId);
        List<OrderProduct> list = orderProductService.selectOrderProductList(orderProduct);
        if (list.isEmpty() == false && list.size() == 1) {
            return AjaxResult.success(list.get(0));
        }
        return AjaxResult.success();

    }

    @ApiOperation("创建订单")
    @PostMapping("/createOrder")
    public AjaxResult createOrder(@RequestBody Map<String, String> map) {
        System.out.println(map);
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setProQty(Integer.parseInt(map.get("qty")));
        orderProduct.setCreateBy("APP");
        orderProduct.setPpId(map.get("mId"));

        orderProductService.insertOrderProduct(orderProduct);

        return AjaxResult.success();
    }

    @ApiOperation("查询产品")
    @GetMapping("/getProduct")
    public AjaxResult getProduct(Material material) {

        List<Material> list = materialService.selectMaterialList(material);


        return AjaxResult.success(list);

    }

    @ApiOperation("app登录")
    @PostMapping("/login")
    public AjaxResult appLogin(@RequestBody Map<String, String> map) {

        System.out.println(map);
        SysUser user = new SysUser();
        user.setPassword(map.get("password"));
        user.setUserName(map.get("username"));
        List<SysUser> list_u = userService.selectUserList(user);
        if (!list_u.isEmpty() && list_u.size() == 1) {
            SysUser loginUser = list_u.get(0);
            if (SecurityUtils.matchesPassword(user.getPassword(), loginUser.getPassword())) {

                return AjaxResult.success(loginUser);
            }

        }
        return AjaxResult.error();
    }

    //
    @ApiOperation("查询工作进度")
    @GetMapping("/getWorkPI")
    public AjaxResult getWorkPI(WorkPlanItem workPlanItem) {


        List<WorkPlanItem> list = workPlanItemService.selectWorkPlanItemList(workPlanItem);
        Collections.reverse(list);
        return AjaxResult.success(list);

    }

    //获取成品库存
    @ApiOperation("查询成品库")
    @GetMapping("/getProStore")
    public AjaxResult getProStore(WorkPlanItem workPlanItem) {

        List<ProductStoreList> list = productStoreListService.selectProductStoreListList(null);

        return AjaxResult.success(list);

    }


    @ApiOperation("查询设备状态")
    @GetMapping("/getDevState")
    public AjaxResult getDevState() {
        NodeId mes_mode = NodeId.parse("ns=3;s=\"OPC\".\"To_MES\".\"mes_mode\"");// //MES模式节点
        NodeId mes_mode2 = NodeId.parse("ns=4;i=16"); //MES模式节点
        List<ProlSite> list = prolSiteService.selectProlSiteList(null);
        for (ProlSite ps : list) {
            if (OpcUtil.mapOpcClient.containsKey(ps.getSiteId()) && OpcUtil.mapOpcClient.get(ps.getSiteId()) != null) {

                OpcUaClient clent = (OpcUaClient) OpcUtil.mapOpcClient.get(ps.getSiteId());

                //站点不同 节点不一样
                if (clent.getSession().isDone()) {
                    ps.setConState("1");
                    if (ps.getSiteId().equals("gw01")) {
                        ps.setMesState(OpcClientUtil.read(mes_mode, clent));
                    } else {
                        ps.setMesState(OpcClientUtil.read(mes_mode2, clent));
                    }

                }


            }


        }


        return AjaxResult.success(list);


    }

    @ApiOperation("查询每天入库情况")
    @GetMapping("/getRkByTime")
    public AjaxResult getRkByTime() {

        List<Map<String,Object>>  sumList=new ArrayList<>();
        String[] riqi={DateUtils.getPastDate(6),DateUtils.getPastDate(5),DateUtils.getPastDate(4),DateUtils.getPastDate(3),DateUtils.getPastDate(2),DateUtils.getPastDate(1),DateUtils.getDate()};

        for(String d:riqi){
            Map map = new HashMap();
            map.put("rkType", "成品入库");
            map.put("createTime", d);
            StorageInRecord storageInRecord = storageInRecordService.countInByCreateTime(map);
            map.put("rkQty",storageInRecord.getRkQty());

            sumList.add(map);
        }


        return AjaxResult.success(sumList);
    }

    @ApiOperation("查询订单统计情况")
    @GetMapping("/getOrderQtyByDay")
    public AjaxResult getOrderQtyByDay() {




        return AjaxResult.success(orderProductService.findQtyGroupDay());
    }


}
